# -*- coding: utf-8 -*-
# @Date   : 2020/1/17
# @File   : AC07_tx03_Change_Ratio.py
# @Author : zhaochen
'''eof
name:月均申报收入总额_change_ratio
code:AC07_tx03_Change_Ratio
tableName:
columnName:
groups:AC模块
dependencies:EG_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import json

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def isFloat(x):
    '''
    判断x为float类型且大于等于0
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def getRatingInfoData(code, interface=None, last=False):
    '''
    获取上次评级信息的指标值或接口数据，默认返回的格式是tuple(val, "value") 指标值和标记
    标记分为 'value':指标值 'data':数据
    :param code: 要获取的指标值的指标code
    :param interface: EC_DSJ_2D/IC_DSJ_2D/TX_CQ_DSJ
    :return:
    '''
    try:
        historyRatingInfo = json.loads(ratingRequest.get("historyRatingInfo"))
        if last:
            # 获取上次评级数据信息
            ratingInfo = historyRatingInfo.get("lastRatingInfo")
        else:
            # 获取本次评级数据
            ratingInfo = historyRatingInfo.get("ratingInfo")
        # 如果是取score 或者 ratingLevel 直接返回
        if code in ["score", "ratingLevel"]:
            score = ratingInfo.get(code)
            try:
                return float(score), "value"
            except:
                return None, None
        # 取数据类型进行判断
        dataType = ratingInfo.get("dataType")
        # 如果传回来是数据 则返回相应接口里面的数据data
        if dataType == "1":
            data = ratingInfo.get(interface).get("data")
            if isinstance(data, dict):
                return (data, "data")
            else:
                return None, None
        # 如果传回来是指标值，则通过code进行提取
        elif dataType == "2":
            val = ratingInfo.get(code)
            if val in null_type_list:
                return None, None
            else:
                try:
                    return float(val), "value"
                except:
                    return None, None
        else:
            return None, None
    except:
        return None, None

def getTable(data, table_name):
    '''
    通过传入的data，获取表
    :param x:
    :return:
    '''
    try:
        table = data.get(table_name)
        if table in null_type_list:
            return None
        else:
            return table if isinstance(table, list) and len(table) > 0 else [{}]
    except:
        return None


def TaxerType(data):
    try:
        syptSwdjxx = getTable(data, 'syptSwdjxx')
        if syptSwdjxx == [{}] or syptSwdjxx is None:
            return None
        else:
            NSRZG_DM = syptSwdjxx[0].get('NSRZG_DM')
            if NSRZG_DM in null_type_list:
                return None
            elif NSRZG_DM not in null_type_list and NSRZG_DM in ['201', '202', '203', '204', '205']:
                return NSRZG_DM
            else:
                return u'其他'
    except:
        return None

#一般纳税人
def ybnsr(data):
    try:
        syptZzsybnsr = getTable(data,'syptZzsybnsr')
        if syptZzsybnsr is None or syptZzsybnsr == [{}]:
            return None
        else:
            # 可能存在统一年月 存在多次数据需要 用dict去重
            revenue = {}
            flag = []
            for i in syptZzsybnsr:
                ND = i.get('ND')
                YF = i.get('YF')
                noneCont = 0
                if ND not in null_type_list and YF in ['01', '02', '03', '04', '05', '06', '07',
                                                       '08', '09', '10', '11', '12']:
                    # 按适用税率计税销售额(ASYSLJSDNSJCYBJSE)
                    if isFloat(i.get('ASYSLJSDNSJCYBJSE')):
                        a1 = float(i.get('ASYSLJSDNSJCYBJSE'))
                    else:
                        a1 = 0
                        noneCont += 1
                    # “按简易办法计税销售额(AJYZSBFZSHWXSE)”
                    if isFloat(i.get('AJYZSBFZSHWXSE')):
                        a2 = float(i.get('AJYZSBFZSHWXSE'))
                    else:
                        a2 = 0
                        noneCont += 1
                    # 免、抵、退办法出口销售额(MDTBFCKHWXSE)
                    if isFloat(i.get('MDTBFCKHWXSE')):
                        a3 = float(i.get('MDTBFCKHWXSE'))
                    else:
                        a3 = 0
                    # 免税销售额(MSHWJLWXSE)
                    if isFloat(i.get('MSHWJLWXSE')):
                        a4 = float(i.get('MSHWJLWXSE'))
                    else:
                        a4 = 0
                        noneCont += 1
                    if noneCont == 4:
                        flag.append(None)
                    else:
                        # 存入每个月的收入
                        revenue.update({ND + YF: a1+a2+a3+a4})
            if revenue == {} or len(flag) == len(syptZzsybnsr):
                return None
            else:
                return float(sum(list(revenue.values()))) / float(len(revenue))
    except:
        return None

#小规模纳税人
def xgm(data):
    try:
        syptZzsxgm = getTable(data, 'syptZzsxgm')
        if syptZzsxgm is None or syptZzsxgm == [{}]:
            return None
        else:
            revenue = {}
            flag = []
            for i in syptZzsxgm:
                ND = i.get('ND')
                YF = i.get('YF')
                noneCount = 0
                if ND not in null_type_list and YF in ['01', '02', '03', '04', '05', '06', '07',
                                                       '08', '09', '10', '11', '12']:
                    # “应征增值税货物及劳务不含税销售额(YZZZSHWJLWBHSXSEBNBQ)”
                    if isFloat(i.get('YZZZSHWJLWBHSXSEBNBQ')):
                        a1 = float(i.get('YZZZSHWJLWBHSXSEBNBQ'))
                    else:
                        a1 = 0
                        noneCount += 1
                    # “销售、出租不动产不含税销售额(XSCZBDCBHSXSE)”
                    if isFloat(i.get('XSCZBDCBHSXSE')):
                        a2 = float(i.get('XSCZBDCBHSXSE'))
                    else:
                        a2 = 0
                        noneCount += 1
                    # “销售使用过的应税固定资产不含税销售额(XSSYGDYSGDZCBHSXSEBNBQ)”
                    if isFloat(i.get('XSSYGDYSGDZCBHSXSEBNBQ')):
                        a3 = float(i.get('XSSYGDYSGDZCBHSXSEBNBQ'))
                    else:
                        a3 = 0
                        noneCount += 1
                    # “免税货物及劳务销售额(MSHWJLWXSEBNBQ)”
                    if isFloat(i.get('MSHWJLWXSEBNBQ')):
                        a4 = float(i.get('MSHWJLWXSEBNBQ'))
                    else:
                        a4 = 0
                        noneCount += 1
                    #出口免税货物销售额(CKMSHWXSEBNBQ)
                    if isFloat(i.get('CKMSHWXSEBNBQ')):
                        a5 = float(i.get('CKMSHWXSEBNBQ'))
                    else:
                        a5 = 0
                        noneCount += 1
                    # 字段都有问题
                    if noneCount == 5:
                        flag.append(None)
                    else:
                        revenue.update({ND+YF: a1+a2+a3+a4+a5})
                else:
                    flag.append(None)
            if revenue == {} or len(flag) == len(syptZzsxgm):
                return None
            else:
                return float(sum(list(revenue.values()))) / float(len(revenue))
    except:
        return None

def TX02_MonthlyIncomeReportAmt(data):
    try:
        taxerType = TaxerType(data)
        # 一般纳税人
        if taxerType in ['201', '202', '203']:
            result = ybnsr(data)
            if result is not None:
                return round(result, 4)
            else:
                return u'缺失值'
        #小规模
        elif taxerType in ['204', '205']:
            result = xgm(data)
            if result is not None:
                return round(result, 4)
            else:
                return u'缺失值'
        #其他情况
        elif taxerType is None or taxerType == '其他':
            syptZzsxgm = getTable(data, 'syptZzsxgm')
            syptZzsybnsr = getTable(data, 'syptZzsybnsr')
            # 二者均为空
            if (syptZzsybnsr is None or syptZzsybnsr == [{}]) and (syptZzsxgm is None or syptZzsxgm == [{}]):
                return u'缺失值'
            # 二者均不为空
            elif syptZzsxgm not in [None, [{}]] and syptZzsybnsr not in [None, [{}]]:
                # 取出小规模纳税人表 和 一般纳税人表中 缴税年度和月份进行比较
                ybnsr_list = []
                xgm_list = []

                for i in syptZzsxgm:
                    ND = i.get('ND')
                    YF = i.get('YF')
                    try:
                        d = ND + YF
                    except:
                        continue
                    if isFloat(d):
                        xgm_list.append(float(d))
                    else:
                        pass

                for i in syptZzsybnsr:
                    ND = i.get('ND')
                    YF = i.get('YF')
                    try:
                        d = ND + YF
                    except:
                        continue
                    if isFloat(d):
                        ybnsr_list.append(float(d))
                    else:
                        pass

                if ybnsr_list == [] and xgm_list == []:
                    return u'缺失值'
                elif ybnsr_list != [] and xgm_list != []:
                    if max(ybnsr_list) >= max(xgm_list):
                        result = ybnsr(data)
                        if result is not None:
                            return round(result, 4)
                        else:
                            return u'缺失值'
                    else:
                        result = xgm(data)
                        if result is not None:
                            return round(result, 4)
                        else:
                            return u'缺失值'
                elif ybnsr_list != [] and xgm_list == []:
                    result = ybnsr(data)
                    if result is not None:
                        return round(result, 4)
                    else:
                        return u'缺失值'
                elif ybnsr_list == [] and xgm_list != []:
                    result = xgm(data)
                    if result is not None:
                        return round(result, 4)
                    else:
                        return u'缺失值'
                else:
                    assert False
            #一般纳税人表为空 小规模不为空 用小规模纳税表计算
            elif syptZzsybnsr in [None, [{}]] and syptZzsxgm not in [None, [{}]]:
                result = xgm(data)
                if result is not None:
                    return round(result, 4)
                else:
                    return u'缺失值'
            #一般纳税人不为空 小规模为空 用一般纳税人表计算
            elif syptZzsybnsr not in [None, [{}]] and syptZzsxgm in [None, [{}]]:
                result = ybnsr(data)
                if result is not None:
                    return round(result, 4)
                else:
                    return u'缺失值'
        else:
            assert False
    except:
        return u'缺失值'

'''
1、分别提取[本次评级信息]和[上次评级信息]里的“月均申报收入总额”；             
2、Factor1=[本次评级信息]月均申报收入总额；       
3、Factor2=[上次评级信息]月均申报收入总额；       
4、Factor=Factor2/(Factor1-Factor2)    
'''

def factor1():
    # Factor1=[本次评级信息]月均申报收入总额；
    data, data_type = getRatingInfoData('TX02_MonthlyIncomeReportAmt', interface='TX_CQ_DSJ', last=False)
    if data_type == 'value':
        return data
    elif data_type == 'data':
        return TX02_MonthlyIncomeReportAmt(data)
    else:
        return None


def factor2():
    #Factor2=[上次评级信息]月均申报收入总额；
    data, data_type = getRatingInfoData('TX02_MonthlyIncomeReportAmt', interface='TX_CQ_DSJ', last=True)
    if data_type == 'value':
        return data
    elif data_type == 'data':
        return TX02_MonthlyIncomeReportAmt(data)
    else:
        return None


def AC07_tx03_Change_Ratio():
    f1 = factor1()
    f2 = factor2()
    try:
        res = (float(f1) - float (f2)) / float(f2)
        return round(res,4)
    except:
        return u'缺失值'


result = AC07_tx03_Change_Ratio()
